package com.utils.httphelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/*
 * HTTP接受xml报文请求并解析
 * 
 * 通过HTTP接受请求，并读取数据是字符串格式的，分为有根节点和没有根节点 1、在以XML的Document对象解析字符串，转成Document对象
 * 再获得根节点和节点 2、用String的split("A")[1].split("/A").[0];获取节点A的数据
 */
public class AcceptXMLServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final String DEFAULT_CHARSET = "UTF-8";

	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doPost(req, res);
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@SuppressWarnings("unused")
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		req.setCharacterEncoding(DEFAULT_CHARSET);

		// 报文 流解析方式

		BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) req.getInputStream()));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		res.setCharacterEncoding(DEFAULT_CHARSET);
		// String transXML="<?xml version='1.0'
		// encoding='utf-8'?><root><Header><Name>朱虹</Name><Mobile>18566042536</Mobile><CardNo>51253219810414003X</CardNo><Source>SDAPP</Source><ApplyCode>M20150605000079</ApplyCode></Header><body><LoanLife>12</LoanLife><LoanAmount>150000</LoanAmount><LoanPurpose>64</LoanPurpose><Respsales>08530159</Respsales><Operator></Operator><ProductCode>privateEn</ProductCode><DeptId>延庆</DeptId><BranchCode>00020300</BranchCode><SourceOfBusiness>8</SourceOfBusiness><distributeChannel>9</distributeChannel><RiskCode>2208</RiskCode><Bank>FOTIC</Bank><BankBranchCode></BankBranchCode><ChannelType>N114</ChannelType><EduBg>10</EduBg><MaritalStatus>1</MaritalStatus><Phone>010-3247661</Phone><AddressDetail>地方</AddressDetail><AddressProvince>北京市</AddressProvince><AddressCity>北京市</AddressCity><AddressDistrict>东城区</AddressDistrict><DisputeProcessingWay>1</DisputeProcessingWay><FamilySize>4</FamilySize><PostCode>343333</PostCode><AddressLivedStartTime>2015-06-05</AddressLivedStartTime><CityLivedStartTime>2015-06-05</CityLivedStartTime><HousePropertyType>1</HousePropertyType><HousePurchaseTime>2015-06-05</HousePurchaseTime><HouseArea>43</HouseArea><HouseHoldProvince>北京市</HouseHoldProvince><HouseHoldCity>北京市</HouseHoldCity><HouseHoldDistrict>东城区</HouseHoldDistrict><CarInfo>0</CarInfo><HasSocialSecurity>1</HasSocialSecurity><HousingExpenditure>342</HousingExpenditure><Company>额外人人</Company><CompanyType>1</CompanyType><UnitKind>A</UnitKind><Dept>地方</Dept><Position>0</Position><CompanyAddress>付多</CompanyAddress><CompanyAddressProvince>北京市</CompanyAddressProvince><CompanyAddressCity>北京市</CompanyAddressCity><CompanyAddressDistrict>东城区</CompanyAddressDistrict><CompanyPhone>010-3247661</CompanyPhone><CompanyWorkStartTime>2015-06-05</CompanyWorkStartTime><TotalIncome>123123</TotalIncome><CompanyPostCode>342342</CompanyPostCode><SalaryLevel>0</SalaryLevel><PayDay>12</PayDay><IncomeFlag>1</IncomeFlag><SpouseName></SpouseName><SpouseMobile></SpouseMobile><SpouseContactWay></SpouseContactWay><LrName>潍坊</LrName><LrRelationship>02</LrRelationship><LrMobile>18202791491</LrMobile><OcName1>发斯蒂芬</OcName1><OcRelationship1>06</OcRelationship1><OcMobile1>18202791491</OcMobile1><OcName2>玩儿</OcName2><OcRelationship2>06</OcRelationship2><OcMobile2>18202791491</OcMobile2><OcName3>潍坊</OcName3><OcRelationship3>06</OcRelationship3><OcMobile3>18202791491</OcMobile3><FamilyKnow>1</FamilyKnow><PostAddress>0</PostAddress><IsPrivateEnOwner>1</IsPrivateEnOwner><PrivateOwner><PrivateEnType>1</PrivateEnType><FoundTime>2015-06-05</FoundTime><Premises>0</Premises><Employees>324</Employees><StockRatio>32</StockRatio></PrivateOwner></body></root>";
		String returnXML = "";
		String transXML = sb.toString();
		if (transXML.contains("<PACKET>")) {
			System.out.print("接收到的报文为：  " + transXML);
			try {
				String cardNo = transXML.split("<CardNo>")[1].split("</CardNo>")[0]; // 客户身份证号
				// 1.解析报文及数据校验
				String mess = parsingApplyRegistXML(transXML);
				// 2. 数据落地失败
			} catch (Exception e) {
				System.out.print(e.getMessage());
				PrintWriter outErr = res.getWriter();
				outErr.print("input parameter error");
			} finally {
				PrintWriter out = res.getWriter();
				out.print(returnXML);
				out.flush();
				out.close();
			}
		} 
	}

	/**
	 * 解析展业APP传入报文
	 * 
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public String parsingApplyRegistXML(String xmlBody) throws Exception {

		// 1.获得解析文档
		Document doc = DocumentHelper.parseText(xmlBody);
		Element rootElt = doc.getRootElement();
		// 2.解析报文头
		Map<String, String> headMap = new HashMap<String, String>();
		Iterator iter = rootElt.elementIterator("Header");    // 获取根节点下的子节点Header

		while (iter.hasNext()) {
			Element recordEle = (Element) iter.next();
			headMap.put("source", recordEle.elementTextTrim("Source"));
		}
		// 3.校验报文头
		// 4.解析报文体
		Iterator body = rootElt.elementIterator("body"); // 获取根节点下的子节点body
		while (body.hasNext()) {
			Element node = (Element) body.next();
			headMap.put("ApplyCode",node.elementTextTrim("ApplyCode"));
		}
		// 5.校验报文体是否合法
		// 6.执行数据存储操作
		return null;
	}
}
